package org.ouwh.oowiki.http;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.ouwh.fw.model.data.Struct;
import org.ouwh.fw.model.service.ServiceContainer;
import org.ouwh.oowiki.GlobalConstants;

public class HttpResponsePresenter {
	public void present(HttpServletResponse response, MyResponse myResponse)
			throws Exception {
		Struct results = myResponse.getResults();
		String html = translateToHtml(results);
		response.setContentType("text/html;charset=" + GlobalConstants.CHAR_SET);
		response.getOutputStream().write(
				html.toString().getBytes(GlobalConstants.CHAR_SET));
		response.flushBuffer();
	}

	private String translateToHtml(Struct results) throws Exception {
		VelocityEngine ve = ((VelocityService) ServiceContainer.getService("velocity")).getEngine();
	    Template t = ve.getTemplate((String)results.getValueAt("Template"), GlobalConstants.CHAR_SET);
	    VelocityContext ctx = new VelocityContext();
	    for (String name : results.keySet()) {
	    	ctx.put(name, results.getValueAt(name));
	    };
	    
	    StringWriter sw = new StringWriter();
	    t.merge(ctx, sw);
		return sw.toString();
	}

}
